//
//  UTConnectorViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/4.
//

import UIKit

class UTConnectorViewController: UTBaseViewController {
    
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var linkTextField: UITextField!
    @IBOutlet weak var browsingHistoryTextView: UITextView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionHeight: NSLayoutConstraint!
    
    lazy var data: UTConnectorModel = {
        if let data = UTConnectorHelper.connectorInfo() {
            return data
        }
        let data = UTConnectorModel()
        if data.items.count == 0 {
            for i in 0...7 {
                let model = UTConnectorConvenientLinkModel()
                switch i {
                case 0:
                    model.icon = "tb"
                    model.name = "淘宝"
                    model.link = "https://www.taobao.com"
                    model.isTop = false
                case 1:
                    model.icon = "jd"
                    model.name = "京东"
                    model.link = "https://www.jd.com"
                    model.isTop = false
                case 2:
                    model.icon = "pdd"
                    model.name = "拼多多"
                    model.link = "https://www.pinduoduo.com"
                    model.isTop = false
                case 3:
                    model.icon = "wph"
                    model.name = "唯品会"
                    model.link = "https://www.vip.com"
                    model.isTop = false
                case 4:
                    model.icon = "ymc"
                    model.name = "亚马逊"
                    model.link = "https://www.amazon.com"
                    model.isTop = false
                case 5:
                    model.icon = "snyg"
                    model.name = "苏宁易购"
                    model.link = "https://www.suning.com"
                    model.isTop = false
                case 6:
                    model.icon = "xc"
                    model.name = "携程旅行"
                    model.link = "https://www.ctrip.com"
                    model.isTop = false
                case 7:
                    model.icon = "12306"
                    model.name = "12306"
                    model.link = "https://www.12306.cn/index/"
                    model.isTop = false
                default:
                    break
                }
                data.items.append(model)
            }
            UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
        }
        return data
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        loadData()
    }

    fileprivate func setupViews() {
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        browsingHistoryTextView.delegate = self
        browsingHistoryTextView.contentInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
        let flowLayout =  UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 54, height: 82)
        flowLayout.minimumInteritemSpacing = (UIScreen.main.bounds.size.width - 39 - 54 * 4) / 3
        flowLayout.minimumLineSpacing = 20
        self.collectionView.collectionViewLayout = flowLayout
        self.collectionView.showsVerticalScrollIndicator = false
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(nibName: "UTConnectorConvenientLinkViewCell", bundle: nil), forCellWithReuseIdentifier: "UTConnectorConvenientLinkViewCell")
    }
    
    fileprivate func loadData() {
        if let data = UTConnectorHelper.connectorInfo() {
            self.data = data
        }
        data.records = Array(data.records.reversed())
        let linkString = data.records.map { $0.link ?? "" }.joined(separator: "\n")
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10
        let attributes: [NSAttributedString.Key: Any] = [
            .paragraphStyle: paragraphStyle,
            .font: UIFont.systemFont(ofSize: 16)
        ]
        let attributedText = NSAttributedString(string: linkString, attributes: attributes)
        browsingHistoryTextView.attributedText = attributedText
        data.items = data.items.sorted { $0.isTop && !$1.isTop }
        self.collectionView.reloadData()
        self.collectionView.layoutIfNeeded()
        collectionHeight.constant = self.collectionView.collectionViewLayout.collectionViewContentSize.height
    }
    
    @IBAction func goBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @IBAction func goOpenLink(_ sender: UIButton) {
        if let text = linkTextField.text, text.isEmpty, !text.contains( "http") {
            self.view.makeToast("请输入正确链接", position: .center)
            return
        }
        if data.records.count > 7 {
            data.records.removeFirst()
        }
        let model = UTConnectorConvenientLinkModel()
        model.icon = "icon_df"
        model.name = "默认"
        model.link = linkTextField.text ?? ""
        model.isTop = false
        data.records.append(model)
        UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
        loadData()
        let vc = UTConnectorWebViewController()
        vc.model = model
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func addConvenientLink(_ sender: UIButton) {
        let vc = UTAddConvenientLinkViewController()
        vc.modalPresentationStyle = .overFullScreen
        present(vc, animated: false)
        vc.reloadData = {
            self.loadData()
        }
    }
}

extension UTConnectorViewController: UITextViewDelegate {
    // 实现 UITextViewDelegate 方法来处理链接点击事件
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if data.records.count > 7 {
            data.records.removeFirst()
        }
        let model = UTConnectorConvenientLinkModel()
        model.icon = "icon_df"
        model.name = "默认"
        model.link = URL.absoluteString
        model.isTop = false
        data.records.append(model)
        UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
        loadData()
        let vc = UTConnectorWebViewController()
        vc.model = model
        self.navigationController?.pushViewController(vc, animated: true)
        return false
    }
}

extension UTConnectorViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UTConnectorConvenientLinkViewCell", for: indexPath) as? UTConnectorConvenientLinkViewCell else {
            fatalError("Unable to dequeue cell")
        }
        cell.model = data.items[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = data.items[indexPath.row]
        if data.records.count > 7 {
            data.records.removeFirst()
        }
        data.records.append(model)
        UTConnectorHelper.dc_saveTaskCounterInfo(connector: data)
        loadData()
        let vc = UTConnectorWebViewController()
        vc.model = model
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

